package com.aaa.controller;

import com.aaa.dao.UserinfoDao;
import com.aaa.dao.impl.UserinfoDaoImpl;
import com.aaa.entity.MyReturn;
import com.aaa.utils.Constants;
import com.aaa.utils.RetStatusEnum;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet",urlPatterns ="/login")
public class LoginServlet extends HttpServlet {
    UserinfoDao userinfoDao=new UserinfoDaoImpl();
   @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将所有的参数存入一个map集合中
        Map<String,Object> map=new HashMap<>();
        //获取所有的参数名集合
        Enumeration<String> parameterNames=request.getParameterNames();
        //遍历所有的参数名
        while (parameterNames.hasMoreElements()){
            //获取第一个参数名
            String key=parameterNames.nextElement();
            //根据参数名获取参数值
            Object value=request.getParameter(key);
            //将参数名和参数值存入mao集合中
            map.put(key,value);
        }
        MyReturn myReturn=new MyReturn();
        switch (map.get("method")+""){
            case "login":
                if(userinfoDao.checkUser(map)){
                    request.getSession().setAttribute("username",map.get("searchUserName").toString());
                    myReturn.setCode(RetStatusEnum.SUCCESS.getCode());
                }else {
                    myReturn.setCode(RetStatusEnum.FAILE.getCode());
                    myReturn.setMsg(Constants.ERROR_CODE);
                }
                break;
            default:
                System.out.println("不支持的方法");
                break;
        }
        //将返回的数据对象进行json字符串转换
        String jsonString= JSON.toJSONString(myReturn);
        response.getWriter().write(jsonString);
    }


}
